<template>
  <div class="project-management-container">
    <el-button type="primary" @click="openDialog">创建项目</el-button>
    <div class="project-cards">
      <el-card v-for="(project, index) in projects" :key="index" class="project-card">
        <div class="project-info">
          <p><strong>项目名称：</strong>{{ project.projectName }}</p>
          <p><strong>评估方法：</strong>{{ project.evaluationMethod }}</p>
          <p><strong>计算模型：</strong>{{ project.calculationModel }}</p>
          <p><strong>项目状态：</strong>{{ project.status }}</p>
        </div>
        <el-button 
          v-if="project.status === '未提交'" 
          type="primary" 
          @click="beginEvaluation(index)"
        >
          评估
        </el-button>
        <span v-if="project.status === '评估中...'">评估中...</span>
        <el-button 
          v-if="project.status === '下一步'" 
          type="success" 
          @click="goToNextStep"
        >
          下一步
        </el-button>
      </el-card>
    </div>

    <el-dialog :visible.sync="dialogVisible" title="创建新项目" width="50%">
      <el-form :model="form" label-width="120px" :rules="rules" ref="form" status-icon>
        <el-form-item label="项目名称" prop="projectName" required>
          <el-input v-model="form.projectName" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        
        <el-form-item label="评估方法" prop="evaluationMethod" required>
          <el-select v-model="form.evaluationMethod" placeholder="请选择评估方法">
            <el-option label="估算功能点法" value="method1"></el-option>
            <el-option label="方法二" value="method2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="计算模型" prop="calculationModel" required>
          <el-select v-model="form.calculationModel" placeholder="请选择计算模型">
            <el-option label="智谱清言（推荐）" value="model1"></el-option>
            <el-option label="Chatgpt" value="model2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="上传文件" prop="fileList">
          <el-upload
            :action="'http://localhost:8080/project'"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".doc,.docx"
            :limit="1"
            :headers="uploadHeaders"
            :data="{ userId: userId }"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ProjectManagement',
  data() {
    return {
      dialogVisible: false,
      form: {
        projectName: '',
        evaluationMethod: '',
        calculationModel: '',
      },
      fileList: [],
      projects: [],
      rules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
        evaluationMethod: [
          { required: true, message: '请选择评估方法', trigger: 'change' }
        ],
        calculationModel: [
          { required: true, message: '请选择计算模型', trigger: 'change' }
        ],
      },
      userId: 2,
      uploadHeaders: {
        'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes',
        'userId': this.userId
      }
    }
  },
  methods: {
    openDialog() {
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    beforeUpload(file) {
      const isWord = file.type === 'application/msword' || file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      if (!isWord) {
        this.$message.error('上传文件只能是 Word 格式!');
      }
      return isWord;
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1);
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid && this.fileList.length > 0) {
          const formData = new FormData();
          formData.append('file', this.fileList[0].raw);
          formData.append('projectName', this.form.projectName);
          formData.append('userId', this.userId);

          axios.post('http://localhost:8080/project', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
            }
          })
          .then(response => {
            this.$message.success('项目已创建并提交到服务器');
            const newProject = {
              projectName: this.form.projectName,
              evaluationMethod: this.form.evaluationMethod,
              calculationModel: this.form.calculationModel,
              status: '未提交',
              id: response.data.id // 自定义id
            };
            this.projects.push(newProject);
            this.closeDialog();
            this.resetForm();
          })
          .catch(error => {
            this.$message.error('提交项目失败');
            console.error('Error:', error);
          });
        } else {
          this.$message.error('请完整填写所有信息并上传文件');
        }
      });
    },
    resetForm() {
      this.form = {
        projectName: '',
        evaluationMethod: '',
        calculationModel: '',
      };
      this.fileList = [];
    },
    beginEvaluation(index) {
      const project = this.projects[index];
      axios.post(`http://localhost:8080/project/begin/${project.id}`, null, {
        headers: {
          'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
        }
      })
      .then(() => {
        project.status = '评估中...';
        this.pollProjectStatus(project.id, index);
      })
      .catch(error => {
        this.$message.error('评估启动失败');
        console.error('Error:', error);
      });
    },
    pollProjectStatus(projectId, index) {
      const poll = setInterval(() => {
        axios.get(`http://localhost:8080/project/status?id=${projectId}`, {
          headers: {
            'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
          }
        })
        .then(response => {
          if (response.data.code === 1) {
            clearInterval(poll);
            this.projects[index].status = '下一步';
          }
        })
        .catch(error => {
          console.error('Error polling project status:', error);
        });
      }, 3000);
    },
    goToNextStep() {
      this.$router.push({ name: 'ProjectConfirm' });
    }
  }
}
</script>

<style scoped>
.project-management-container {
  padding: 20px;
}

.project-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.project-card {
  width: 300px;
  border: 1px solid #ebebeb;
  padding: 15px;
}

.project-info {
  margin-bottom: 10px;
}
</style>
